package com.thesis.conectify;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.thesis.client.JSONParser;
import com.thesis.object.Bill;
import com.thesis.object.DishDetailAddBill;
import com.thesis.object.ListBill;
import com.thesis.object.ListBillDescription;
import com.thesis.object.ListDishType;
import com.thesis.object.ListDishes;
import com.thesis.object.ListServeTableDetail;
import com.thesis.object.ListTable;
import com.thesis.object.ListUsers;
import com.thesis.object.ServeTableDetail;
import com.thesis.object.Session;
import com.thesis.object.Table;

/**
 * Connectify Class
 * 
 * connect to server, get detail from server or do some action
 * 
 * @author NgocTuyen
 * 
 */

public class Connectify {
	// base url:
	
	
	
	String baseUrl = "http://192.168.1.100:8080/Server/";
	
	JSONParser jsonParser = new JSONParser();

	Session session;
	

	/**
	 * Constructor function
	 * 
	 * Constructor
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public Connectify() {
		// TODO Auto-generated constructor stub
		session = Session.getInstance();
		
	}

	/**
	 * login function
	 * 
	 * send request login to server and get result from server, set data to
	 * Session singleton class.
	 * 
	 * @access public
	 * 
	 * @param username
	 *            Username of account
	 * @param password
	 *            Password of account
	 * @return boolean + role of account login: if login success + 9: if login
	 *         false
	 */
	public int[] login(String username, String password) {
		// set Login url
		String url = baseUrl + "ClientLogin/login"  ;
		Log.d("login test", url);
		// set params of url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));

		// send request and get json
		JSONObject json = null;
		
		try {
			json = jsonParser.makeHttpRequest(url, "GET", params);
		}catch(Exception e){
			
			int[] a = { 8, 0, 0 };
			return a;
		}
			

		
		Log.d("objectjson", "" + json);
		String status;
		try {
			// get result status
			status = json.getString("status");
			if (status.compareTo("fail") == 0) {
				// return false if login false
				int[] a = { 9, 0, 0 };
				return a;
			} else {
				// login success
				// get id, ci_session and role of account
				int id = Integer.parseInt(json.getJSONObject("user_info")
						.getString("_id"));
				int managerId;

				String ci_session = json.getString("ci_session");
				int role = Integer.parseInt(json.getJSONObject("user_info")
						.getString("role"));
				session.setSession(id, username, ci_session, role);
				if (role == 0) {
					managerId = Integer
							.parseInt(json.getJSONObject("user_info")
									.getString("manager_id"));
				} else {
					managerId = 0;
				}
				int[] a = { role, id, managerId };
				return a;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			int[] a = { 9, 0, 0 };
			return a;
		}
	}

	/**
	 * getAllTable function
	 * 
	 * send request get all table to server and get json result
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return ListTable + null: if get all table false + ListTable object: if
	 *         get all table success
	 */
	public ListTable getAllTable() {
		// set get all table url
		String url = baseUrl + "ClientTable/all_table_detail";

		// get ci_session from singleton Session
		String ci_session = session.getCI_Session();

		// set params of url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));

		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		// Log.d("JSON TABLE", ""+json);

		try {
			// get status from server
			String status = json.getString("status");
			if (status.compareTo("fail") == 0) {
				// fail to get all table
				return null;
			} else {
				// get all table success
				// get JSONArray from server
				JSONArray listTableArray = json.getJSONArray("info");

				// set result to listTable variable
				ListTable listTable = new ListTable();
				listTable.addTableByJson(listTableArray);

				Log.d("JSONALLTABLE",
						Integer.toString(listTable.getListTable().size()));

				return listTable;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * getAllUsers function
	 * 
	 * send request get all users to server and get json result
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return ListUsers + null: if get all users fail + ListUsers object: if
	 *         get all users success
	 */
	public ListUsers getAllUsers() {
		// set get all users url
		String url = baseUrl + "ClientUser/all_user_detail";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to get all users url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		Log.d("JSON USER", "" + json);

		try {
			// get status of result
			String status = json.getString("status");
			if (status.compareTo("fail") == 0) {
				// fail to get all users
				return null;
			}
			// success to get all users
			// get all users info
			JSONArray listUserArray = json.getJSONArray("info");

			ListUsers listUsers = ListUsers.getInstance();

			listUsers.addUserByJson(listUserArray);

			return listUsers;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * deleteUser function
	 * 
	 * send request delete to server and receive result
	 * 
	 * @access public
	 * 
	 * @param id
	 *            : id of user
	 * 
	 * @return ListUsers + null if delete fail + listUsers after delete
	 */
	public ListUsers deleteUser(int id) {
		// set delete user in url
		String url = baseUrl + "ClientUser/delete_user";

		// get ci_session from Session:
		String ci_session = session.getCI_Session();

		// set params to delete user:
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("id", Integer.toString(id)));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		// get status of result
		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				// fail to delete users
				return null;
			}
			// success to delete users
			ListUsers listUsers = ListUsers.getInstance();

			listUsers.deleteUser(id);

			return listUsers;

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * editUser function
	 * 
	 * send edit request edit user to server and receive result
	 * 
	 * @access public
	 * 
	 * @param id
	 *            : id of user
	 * @param firstName
	 *            : first name of user
	 * @param lastName
	 *            : last name of user
	 * @param dateOfBirth
	 *            : birthday of user
	 * @param address
	 *            : address of user
	 * @param phoneNumber
	 *            : phone number of user
	 * 
	 * @return ListUsers + null if edit user fail + list users if edit user
	 *         success
	 */
	public ListUsers editUser(int id, String firstName, String lastName,
			String dateOfBirth, String address, String phoneNumber) {
		// set edit user url
		String url = baseUrl + "ClientUser/edit_user";

		// set ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to edit user:
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("id", Integer.toString(id)));
		params.add(new BasicNameValuePair("first_name", firstName));
		params.add(new BasicNameValuePair("last_name", lastName));
		params.add(new BasicNameValuePair("date_of_birth", dateOfBirth));
		params.add(new BasicNameValuePair("address", address));
		params.add(new BasicNameValuePair("phone_number", phoneNumber));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		Log.d("aaaaaaaa", json.toString());

		// get status of result
		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				// fail to edit users
				return null;
			}

			// success to delete users
			// get all users info
			JSONObject listUserObj = json.getJSONObject("info");

			ListUsers listUsers = ListUsers.getInstance();

			listUsers.editUser(listUserObj);

			return listUsers;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * getListBill function
	 * 
	 * send request get bill to server and get json result
	 * 
	 * @access public
	 * 
	 * @param beginDate
	 *            : begin date of statistics
	 * @param endDate
	 *            : end date of statistics
	 * 
	 * @return ListBill + null if get fail + list bill of get success
	 */
	public ListBill getListBill(String beginDate, String endDate) {
		// set get list bill url
		String url = baseUrl + "ClientStatistics/get_bill_by_date";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to get list bill:
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("begin_date", beginDate));
		params.add(new BasicNameValuePair("end_date", endDate));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		// get status of result
		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				// fail to get list bill
				return null;
			}

			// success to get list bill
			// get all bills info
			JSONArray listBillObj = json.getJSONArray("info");

			ListBill listBills = new ListBill();

			listBills.addBillByJson(listBillObj);

			return listBills;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * getListBillDescription function
	 * 
	 * send request get bill description to server and get json result
	 * 
	 * @access public
	 * 
	 * @param beginDate
	 *            : begin date of statistics
	 * @param endDate
	 *            : end date of statistics
	 * 
	 * @return ListBillDescription + null if get fail + list bill description of
	 *         get success
	 */
	public ListBillDescription getListBillDescription(String beginDate,
			String endDate) {
		// set get list bill url
		String url = baseUrl + "ClientStatistics/get_bill_description_by_date";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to get list bill:
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("begin_date", beginDate));
		params.add(new BasicNameValuePair("end_date", endDate));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		// get status of result

		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				// fail to get list bill
				return null;
			}

			// success to get list bill
			// get all bills info
			JSONArray listBillDescriptionObj = json.getJSONArray("info");

			ListBillDescription listBillsDescription = new ListBillDescription();

			listBillsDescription
					.addBillDescriptionByJson(listBillDescriptionObj);

			return listBillsDescription;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * get list_food which called from day to day () (to statistic food )
	 * 
	 * @param ]day from , day to
	 * @return ListFood
	 */

	/**
	 * getListDishes function
	 * 
	 * send request get all dishes to server and get json result
	 * 
	 * @access public
	 * 
	 * @param void
	 * 
	 * @return ListDishes + null if get all dishes fail + list dishes if get all
	 *         dishes success
	 */
	public ListDishes getListDishes() {
		// set delete user in url
		String url = baseUrl + "ClientDish/all_dish_detail";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to get all users url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		// get status of result
		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				// fail to get all Dishes
				return null;
			}
			// success to get all dishes
			// get JSONArray from server
			JSONArray listDishesArray = json.getJSONArray("info");

			ListDishes listDishes = ListDishes.getInstance();

			listDishes.addDishByJson(listDishesArray);

			return listDishes;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * pickTable function
	 * 
	 * pick table and create new bill.
	 * 
	 * @access public
	 * 
	 * @param tableId
	 *            : id of table which customer pick
	 * @param listExtraTable
	 *            : list extra table of pick table
	 * 
	 * @return boolean + false: if pick table fail + true: if pick table success
	 */
	public Bill pickTable(int tableId, ArrayList<Integer> listExtraTable) {
		// set pick table in url
		String url = baseUrl + "ClientAction/create_new_bill";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set list extra table
		String listExtra = "[";
		for (Integer extraTable : listExtraTable) {
			if (listExtraTable.get(0) == extraTable) {
				listExtra = listExtra + "{\"id\":"
						+ Integer.toString(extraTable) + "}";
			} else {
				listExtra = listExtra + ",{\"id\":"
						+ Integer.toString(extraTable) + "}";
			}
		}

		listExtra = listExtra + "]";
		Log.d("list_extraaaaaaa", listExtra);

		// set params to get all users url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("table_id", Integer.toString(tableId)));
		params.add(new BasicNameValuePair("extra_table", listExtra));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				return null;
			}

			JSONObject billDetail = json.getJSONObject("info");
			Bill bill = new Bill(billDetail.getInt("_id"), billDetail.getInt("user_id"), billDetail.getInt("bill_code"), billDetail.getString("date"), billDetail.getString("start_time"), billDetail.getString("end_time"), billDetail.getInt("table_id"), billDetail.getString("feedback"), billDetail.getInt("total_cost"));
			return bill;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * cancelPickTable function
	 * 
	 * send request to cancel pick table
	 * 
	 * @access public
	 * 
	 * @param tableId
	 *            : id of table cancel pick
	 * 
	 * @return boolean + false: if cancel pick table fail + true: if cancel pick
	 *         table success
	 */
	public boolean cancelPickTable(int tableId) {
		// set pick table in url
		String url = baseUrl + "ClientAction/cancel_bill";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to get all users url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("table_id", Integer.toString(tableId)));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				return false;
			}

			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * bookingTable function
	 * 
	 * get booking table detail, send request to server and receive result
	 * 
	 * @access public
	 * 
	 * @param tableId
	 *            : id of table
	 * @param bookingTime
	 *            : table booking time
	 * @param bookingDescription
	 *            : table booking description
	 * 
	 * @return boolean + true: if booking success + false: if booking fail
	 */
	public boolean bookingTable(int tableId, String bookingTime,
			String bookingDescription) {
		// set booking table in url
		String url = baseUrl + "ClientAction/booking_table";

		// get ci_session from Session
		String ci_session = session.getCI_Session();

		// set params to get all users url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("table_id", Integer.toString(tableId)));
		params.add(new BasicNameValuePair("booking_time", bookingTime));
		params.add(new BasicNameValuePair("booking_description",
				bookingDescription));

		// send request to server and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		try {
			String status = json.getString("status");

			if (status.compareTo("fail") == 0) {
				return false;
			}

			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * getAllDishType function
	 * 
	 * send request get all dish types to server and get json result
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return ListTable + null if get all dish types fail + ListDishType
	 *         object: if get all dish types success
	 */
	public ListDishType getAllDishType() {
		// set get all dish types url
		String url = baseUrl + "ClientDish/all_dish_types";

		// get ci_session from singleton Session
		String ci_session = session.getCI_Session();

		// set params of url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));

		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);

		try {
			// get status from server
			String status = json.getString("status");
			if (status.compareTo("fail") == 0) {
				// fail to get all dish types
				return null;
			} else {
				// get all dish types success
				// get JSONArray from server
				JSONArray listDishTypeArray = json.getJSONArray("info");

				// set result to listDishTypes variable
				ListDishType listDishTypes = ListDishType.getInstance();
				listDishTypes.addDishTypeByJson(listDishTypeArray);

				return listDishTypes;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * addDishToBill function
	 * 
	 * add some dishes to the bill
	 * 
	 * @access public
	 * 
	 * @param billId: id of bill order
	 * @param listDish: list dished order
	 * 
	 * @return boolean:
	 *  + true if add success
	 *  + false: if add fail
	 */
	public boolean addDishToBill(int billId, ArrayList<DishDetailAddBill> listDish){
		// set pick table in url
		String url = baseUrl + "ClientAction/add_dish_to_bill";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		// set list dish order
		String listExtra = "[";
		for (DishDetailAddBill dishDetail : listDish) {
			if (listDish.get(0) == dishDetail) {
				listExtra = listExtra + "{\"id\":\""
					+ Integer.toString(dishDetail.getId()) + "\",";
				listExtra = listExtra + "\"number\":\"" + Integer.toString(dishDetail.getNumber()) + "\"";
				
				if (dishDetail.getFoodNote() != null){
					listExtra = listExtra + ",\"food_note\":\"" + dishDetail.getFoodNote() + "\"";
				}
				listExtra = listExtra + "}";
			} else {
				listExtra = listExtra + ",{\"id\":\""
				+ Integer.toString(dishDetail.getId()) + "\",";
				listExtra = listExtra + "\"number\":\"" + Integer.toString(dishDetail.getNumber()) + "\"";
				
				if (dishDetail.getFoodNote() != null){
					listExtra = listExtra + ",\"food_note\":\"" + dishDetail.getFoodNote();
				}
				listExtra = listExtra + "\"}";
			}
		}

		listExtra = listExtra + "]";
		Log.d("PHITESSTTTT",listExtra);
		
		// set params to add dish order to bill url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("bill_id", Integer.toString(billId)));
		params.add(new BasicNameValuePair("info", listExtra));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			String status = json.getString("status");
			if (status.compareTo("fail") != 0) {
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * getBillOfTable function 
	 * 
	 * get bill of table
	 * 
	 * @access public 
	 * 
	 * @param billId: id of bill in table
	 * 
	 * @return Bill: bill of table
	 */
	public Bill getBillOfTable(int billId){
		// set pick table in url
		String url = baseUrl + "ClientAction/get_bill_detail";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		
		// set params to get bill of dish url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("bill_id", Integer.toString(billId)));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			String status = json.getString("status"); 
			if (status.compareTo("fail") != 0) {
				JSONArray listBillDescriptionObj = json.getJSONArray("bill_description");
				ListBillDescription listBillsDescription = new ListBillDescription();

				listBillsDescription
						.addBillDescriptionByJson(listBillDescriptionObj);
				
				JSONObject billObj = json.getJSONObject("bill");
				Bill bill = new Bill(billObj.getInt("_id"), billObj.getInt("user_id"), billObj.getInt("bill_code"), billObj.getString("date"), billObj.getString("start_time"), billObj.getString("end_time"), billObj.getInt("table_id"), billObj.getString("feedback"), billObj.getInt("total_cost"), listBillsDescription);
				
				return bill;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * getListBillAvailableByUser function
	 * 
	 * get all bill in active of current user
	 * 
	 * @access public
	 * 
	 * @param userId: id of current user
	 * 
	 * @return boolean
	 * + true: if get success
	 * + false: if get fail
	 */
	public ListServeTableDetail getListBillAvailableByUser(int userId){
		// set get all bill available by user in url
		String url = baseUrl + "ClientAction/get_all_bill_by_user";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		
		// set params to get all available bill by user url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("user_id", Integer.toString(userId)));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			String status = json.getString("status");
			if (status.compareTo("fail") == 0) {
				return null;
			}
			Log.d("aaaaaaaaaaa", json.toString());
			JSONArray jsonObj = json.getJSONArray("info");
			ListServeTableDetail listServeTableDetail = ListServeTableDetail.getInstance();
			for (int i = 0; i < jsonObj.length(); i++) {
				JSONObject obj = jsonObj.getJSONObject(i);
				JSONObject table = obj.getJSONObject("table");
				JSONObject bill = obj.getJSONObject("bill");
				Table tableInfo = new Table(table.getInt("_id"), table.getString("name"), table.getInt("number"), table.getInt("manager_id"), table.getString("first_name"), table.getString("last_name"), bill.getInt("user_id"), table.getInt("status_id"), table.getString("status"), /*table.getInt("extra_table")*/ 0, /*table.getInt("booking_status_id")*/0, /*table.getString("booking_status")*/"", /*table.getString("booking_time")*/"", /*table.getString("booking_description")*/"", /*table.getString("desciption")*/"", table.getString("image"));
				JSONArray billDescription = obj.getJSONArray("bill_description");
				ListBillDescription listBillDescription = new ListBillDescription();
				listBillDescription.addBillDescriptionByJson(billDescription);
				
				Bill billInfo = new Bill(bill.getInt("_id"), bill.getInt("user_id"), bill.getInt("bill_code"), bill.getString("date"), bill.getString("start_time"), bill.getString("end_time"), bill.getInt("table_id"), bill.getString("feedback"), /*bill.getInt("total_cost")*/0, listBillDescription);
				ServeTableDetail serveTableDetail = new ServeTableDetail(tableInfo, billInfo);
				listServeTableDetail.addServeTableDetail(serveTableDetail);
			}
			Log.d("aaaaaaaaaaaab", listServeTableDetail.getInstance().getListServeTableDetail().size()+"");
			return listServeTableDetail;
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * downloadUserImage function
	 * 
	 * download all user images in zip file from server
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return boolean + true if download success + false if download fail
	 */
	public boolean downloadUserImage() {
		// This is where we would do the actual download stuff
		// for now I'm just going to loop for 10 seconds
		// publishing progress every second
		String downloadUrl = baseUrl + "assets/img/user.zip";
		int count;
        try {
        	File wallpaperDirectory = new File("/sdcard/restautant/");
			// have the object build the directory structure, if needed.
        	//if (!wallpaperDirectory.exists()){
        		wallpaperDirectory.mkdirs();
        	//}
			
			File outputFile = new File(wallpaperDirectory, "user.zip");

            URL url = new URL(downloadUrl);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            
            // Output stream to write file
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();
            
            // closing streams
            output.close();
            input.close();
            
        } catch (Exception e) {
        	Log.e("Error: ", e.getMessage());
        }
        
        return true;
	}

	/**
	 * downloadDishImage function
	 * 
	 * download all dish images in zip file from server
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return boolean + true if download success + false if download fail
	 */
	public boolean downloadDishImage() {
		// This is where we would do the actual download stuff
		// for now I'm just going to loop for 10 seconds
		// publishing progress every second
		String downloadUrl = baseUrl + "assets/img/dish.zip";
		int count;
        try {
        	File wallpaperDirectory = new File("/sdcard/restautant/");
			// have the object build the directory structure, if needed.
			wallpaperDirectory.mkdirs();
			File outputFile = new File(wallpaperDirectory, "dish.zip");

            URL url = new URL(downloadUrl);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            
            // Output stream to write file
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();
            
            // closing streams
            output.close();
            input.close();
            
        } catch (Exception e) {
        	Log.e("Error: ", e.getMessage());
        }
        
        return true;
	}
	
	/**
	 * downloadTableImage function
	 * 
	 * download all table images in zip file from server
	 * 
	 * @access public
	 * 
	 * @param null
	 * 
	 * @return boolean + true if download success + false if download fail
	 */
	public boolean downloadTableImage() {
		// This is where we would do the actual download stuff
		// for now I'm just going to loop for 10 seconds
		// publishing progress every second
		String downloadUrl = baseUrl + "assets/img/table.zip";
		int count;
        try {
        	File wallpaperDirectory = new File("/sdcard/restautant/");
			// have the object build the directory structure, if needed.
        	//if (!wallpaperDirectory.exists()){
        		wallpaperDirectory.mkdirs();
        	//}
			
			File outputFile = new File(wallpaperDirectory, "table.zip");

            URL url = new URL(downloadUrl);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            
            // Output stream to write file
            OutputStream output = new FileOutputStream(outputFile);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();
            
            // closing streams
            output.close();
            input.close();
            
        } catch (Exception e) {
        	Log.e("Error: ", e.getMessage());
        }
        
        return true;
	}
	
	/**
	 * MODIFY DISH data to bill function
	 * 
	 * MODIFY data dishes which customer called to bill for that table
	 * (for table in serve)
	 * @access public
	 * 
	 * @param 
	 * 	- id table
	 * 	- Arraylist<dishes MODFIFY by customer>
	 * 
	 * @return boolean + true if upload success + false if upload fail
	 */
	public ListBillDescription modifyDishInBill(int billId, ArrayList<DishDetailAddBill> listDish){
		// set modify dish of table in url
		String url = baseUrl + "ClientAction/modify_dishes_of_bill";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		// set list dish modify
		String listExtra = "[";
		for (DishDetailAddBill dishDetail : listDish) {
			if (listDish.get(0) == dishDetail) {
				listExtra = listExtra + "{\"id\":\""
					+ Integer.toString(dishDetail.getId()) + "\",";
				listExtra = listExtra + "\"number\":\"" + Integer.toString(dishDetail.getNumber()) + "\"";
				
				if (dishDetail.getFoodNote() != null){
					listExtra = listExtra + ",\"food_note\":\"" + dishDetail.getFoodNote() + "\"";
				}
				listExtra = listExtra + "}";
			} else {
				listExtra = listExtra + ",{\"id\":\""
				+ Integer.toString(dishDetail.getId()) + "\",";
				listExtra = listExtra + "\"number\":\"" + Integer.toString(dishDetail.getNumber()) + "\"";
				
				if (dishDetail.getFoodNote() != null){
					listExtra = listExtra + ",\"food_note\":\"" + dishDetail.getFoodNote();
				}
				listExtra = listExtra + "\"}";
			}
		}
		listExtra = listExtra + "]";
		
		// set params to add dish modify to bill url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("bill_id", Integer.toString(billId)));
		params.add(new BasicNameValuePair("info", listExtra));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			String status = json.getString("status");
			if (status.compareTo("fail") != 0) {
				JSONArray billDescription = json.getJSONArray("bill_description");
				ListBillDescription listBillDescription = new ListBillDescription();
				listBillDescription.addBillDescriptionByJson(billDescription);
				return listBillDescription;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	 }
	
	/**
	 * DELETE DISH data to bill function
	 * 
	 * DELETE DISH  dishes which customer called to bill for that table 
	 * (for table in serve)
	 * 
	 * @access public
	 * 
	 * @param 
	 * 	- id of bill
	 *  - ArrayList<DishDetailAddBill> list dish delete
	 * 	
	 * 
	 * @return Arraylist<ListBillDescription>
	 */
	 public ListBillDescription deleteDishInBill(int billId, ArrayList<DishDetailAddBill> listDish){
		// set delete dish of table in url
		String url = baseUrl + "ClientAction/delete_dishes_of_bill";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		// set list dish delete
		String listExtra = "[";
		for (DishDetailAddBill dishDetail : listDish) {
			if (listDish.get(0) == dishDetail) {
				listExtra = listExtra + "{\"id\":\""
					+ Integer.toString(dishDetail.getId()) + "\"";
				listExtra = listExtra + "}";
			} else {
				listExtra = listExtra + ",{\"id\":\""
				+ Integer.toString(dishDetail.getId()) + "\"";
				listExtra = listExtra + "\"}";
			}
		}
		listExtra = listExtra + "]";
		
		// set params to add dish order to bill url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("bill_id", Integer.toString(billId)));
		params.add(new BasicNameValuePair("info", listExtra));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			String status = json.getString("status");
			if (status.compareTo("fail") != 0) {
				JSONArray billDescription = json.getJSONArray("bill_description");
				ListBillDescription listBillDescription = new ListBillDescription();
				listBillDescription.addBillDescriptionByJson(billDescription);
				return listBillDescription;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	 }
	 
	 /**
	 * PAYMENT bill function
	 * 
	 * PAYMENT BILL IN THAT TABLE WHICH IN SERVE , INSERT ENDTIME TO THAT BILL AND STATUS SERVE -> AVAILABLE 
	 * (for table in serve)
	 * 
	 * @access public
	 * 
	 * @param 
	 * 	- BILL ID
	 * 	
	 * 
	 * @return BOLSEAN 
	 */
	 
	 public boolean paymentBill(int billId){
		// set get all bill available by user in url
		String url = baseUrl + "ClientAction/billing";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		
		// set params to get all available bill by user url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("bill_id", Integer.toString(billId)));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			// get status from server
			String status = json.getString("status");
			if (status.compareTo("success") == 0) {
				// fail to get all dish types
				return true;
			} else {
				return false;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	 }
	 /**
		 * checkserve dish in bill
		 * 
		 * check dish is served or nit 
		 * (for table in serve)
		 * 
		 * @access public
		 * 
		 * @param 
		 * 	- bill_id 
		 * 	- Arraylist<billdescription_id for that bill>
		 * 
		 * @return BOLSEAN 
		 */
	 public boolean serveDishes(int billId, ArrayList<Integer> listBillDescriptionId){
		// set serve dishes in a bill in url
		String url = baseUrl + "ClientAction/billing";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		
		// set list dish delete
		String listExtra = "[";
		for (Integer dishId : listBillDescriptionId) {
			if (listBillDescriptionId.get(0) == dishId) {
				listExtra = listExtra + "{\"id\":\""
					+ Integer.toString(dishId) + "\"";
				listExtra = listExtra + "}";
			} else {
				listExtra = listExtra + ",{\"id\":\""
				+ Integer.toString(dishId) + "\"";
				listExtra = listExtra + "\"}";
			}
		}
		listExtra = listExtra + "]";
		// set params to serve dishes in a bill url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("bill_id", Integer.toString(billId)));
		params.add(new BasicNameValuePair("info", listExtra));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		try {
			String status = json.getString("status");
			if (status.compareTo("fail") == 0){
				return false;
			}else{
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	 }
	 
	 public void logout(){
		// set serve dishes in a bill in url
		String url = baseUrl + "ClientLogin/logout";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		
		// set params to serve dishes in a bill url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
	 }
	 
	 public boolean cancelBookingTable(int tableId){
		// set serve dishes in a bill in url
		String url = baseUrl + "ClientLogin/logout";
		
		// get ci_session from Session
		String ci_session = session.getCI_Session();
		
		// set params to serve dishes in a bill url
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("ci_session", ci_session));
		params.add(new BasicNameValuePair("table_id", Integer.toString(tableId)));
		
		// send request and get json result
		JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
		
		String status;
		try {
			status = json.getString("status");
			if (status.compareTo("fail") == 0){
				return false;
			}else{
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	 }
}
